package com.ting.test.algorithms.链表;

/**
 * 将一个链表反转
 * <p>
 * 5>4>3>2>1
 * 1>2>3>4>5
 */
public class 双链表反转 {
    public static void main(String[] args) {
        DoubleNode node1 = new DoubleNode(1);
        DoubleNode node2 = new DoubleNode(2);
        DoubleNode node3 = new DoubleNode(3);
        DoubleNode node4 = new DoubleNode(4);
        DoubleNode node5 = new DoubleNode(5);

        node1.next = node2;
        node2.next = node3;
        node2.pre = node1;
        node3.next = node4;
        node3.pre = node2;
        node4.next = node5;
        node4.pre = node3;
        node5.next = null;
        node5.pre = node4;
        DoubleNode node = node1;
//        while (node.next != null) {
//            System.out.println(node.value + ",");
//            node = node.next;
//        }
//        System.out.println(node.value);

        DoubleNode result = fund(node);
        while (result.next != null) {
            System.out.println(result.value + ",");
        }
        System.out.println(result.value);
    }


    //a<>b<>c<>d<>e
    //e<>d<>c<>b<>a

    /**
     * 以c 为例 反转后 c.next=c.pre c.pre=c.next
     *
     * @param head
     * @return
     */
    private static DoubleNode fund(DoubleNode head) {
        DoubleNode pre = null;
        DoubleNode next = null;
        while (head != null) {
            next = head.next;
            head.next = pre;
            head.pre = next;
            pre = head;
            head = next;

        }
        return pre;
    }
}
